package com.miui.theme.custom.utils

import com.miui.theme.custom.data.DatabaseConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet

// 封装JDBC操作的帮助类
class MySQLHelper(private val config: DatabaseConfig) {

    private var connection: Connection? = null

    private val jdbcUrl: String
        get() {
            return "jdbc:mysql://${config.host}:${config.port}/${config.database}?useSSL=false&serverTimezone=UTC"
        }

    init {
        try {
            Class.forName("com.mysql.jdbc.Driver")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 尝试连接数据库
     * 必须在 IO 线程中调用
     */
    suspend fun connect(): Result<Connection> = withContext(Dispatchers.IO) {
        try {
            if (connection != null && !connection!!.isClosed) {
                return@withContext Result.success(connection!!)
            }
            connection = DriverManager.getConnection(jdbcUrl, config.user, config.pass)
            Result.success(connection!!)
        } catch (e: Exception) {
            e.printStackTrace()
            Result.failure(e)
        }
    }

    /**
     * 关闭连接
     */
    suspend fun disconnect() = withContext(Dispatchers.IO) {
        try {
            connection?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 执行查询 (SELECT)
     */
    suspend fun executeQuery(sql: String): Result<ResultSet> = withContext(Dispatchers.IO) {
        try {
            val statement = connect().getOrThrow().createStatement()
            Result.success(statement.executeQuery(sql))
        } catch (e: Exception) {
            e.printStackTrace()
            Result.failure(e)
        }
    }

    /**
     * 执行更新 (INSERT, UPDATE, DELETE, CREATE TABLE)
     */
    suspend fun executeUpdate(sql: String): Result<Int> = withContext(Dispatchers.IO) {
        try {
            val statement = connect().getOrThrow().createStatement()
            Result.success(statement.executeUpdate(sql))
        } catch (e: Exception) {
            e.printStackTrace()
            Result.failure(e)
        }
    }
}